package cn.redsoft.wechatapi.handler;

import java.util.HashMap;
import java.util.Map;

import cn.redsoft.wechatapi.common.exception.NoHandlerMatchedException;
import cn.redsoft.wechatapi.msg.req.RequestMsg;
import cn.redsoft.wechatapi.msg.req.event.EventRequestMsg;
import cn.redsoft.wechatapi.msg.resp.passivity.PassivityResponseMsg;

public class RequestMsgHandlerInvoker {

	public static Map<Class<? extends RequestMsg>, Class<? extends RequestMessageHandler<? extends RequestMsg>>> handlers = new HashMap<Class<? extends RequestMsg>, Class<? extends RequestMessageHandler<? extends RequestMsg>>>();

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public PassivityResponseMsg invokeHandler(RequestMsg req)
			throws NoHandlerMatchedException, InstantiationException,
			IllegalAccessException {
		Class<? extends RequestMessageHandler<? extends RequestMsg>> handlerClass = handlers
				.get(req.getClass());
		if (handlerClass == null) {
			if (req instanceof EventRequestMsg) {
				throw new NoHandlerMatchedException("消息类型 "
						+ req.getMsgType().getValue() + "("
						+ ((EventRequestMsg) req).getEvent().getValue()
						+ ") 尚未提供 Handler .");
			} else {
				throw new NoHandlerMatchedException("<== 消息类型 "
						+ req.getMsgType().getValue() + " 尚未提供 Handler .");
			}
		}
		RequestMessageHandler handler = handlerClass.newInstance();
		return handler.doHandle(req);
	}
}
